package com.example.storage;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_file);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //读取memo文件 显示在输入框
       FileInputStream fis=null;
        try {
            fis = openFileInput("memo");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            ((EditText) findViewById(R.id.file_txt)).setText(new String(buffer));
            fis.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        ((ImageView) findViewById(R.id.quxiao_file)).setOnClickListener(v -> {
            finish();
        });

        ((ImageView) findViewById(R.id.save_file)).setOnClickListener(v -> {
            // 获取输入框的内容
            String st=((EditText) findViewById(R.id.file_txt)).getText().toString();
            // 保存到文件中
            FileOutputStream fos=null;
            try {
                fos = openFileOutput("memo", MODE_PRIVATE);

                fos.write(st.getBytes());
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                // 清除缓存
                fos.flush();
                // 关闭文件输出流

            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }


        });
    }
}